<?php

if( !isset($_GET['jsrq'])){
ini_set('dispaly_errors',1);
ini_set('error_reporting',E_ALL);
}else{
ini_set('dispaly_errors',0);
ini_set('error_reporting', E_ERROR);    
}
include_once('pclzip.lib.php');

define('PATH', getcwd());
define('DS', DIRECTORY_SEPARATOR);
define('DB_USER', "mup_shopu");
define('DB_BASE', "mup_shop");
define('DB_PASS', "RXAmE[_%gxQy");
define('DB_PREFIX', 'SC');

define('FNAME_BASE', 'database.dbf');
define('FNAME_TODELETE', 'todelete.dbf');
define('FNAME_IMAGES', 'images');
define('FNAME_DESCRIPTIONS', 'descriptions');

define('DIR_PROCESS', 'process');
define('DIR_INCOMING', 'data');
define('DIR_SITE_PICTURES', '/published/publicdata/MUPSHOP/attachments/SC/products_pictures/');
define('FPATH_BASE', PATH.DS.DIR_PROCESS.DS.FNAME_BASE );
define('FPATH_TODELETE', PATH.DS.DIR_PROCESS.DS.FNAME_TODELETE );

define('DBA_READ_LIMIT', 1000 );

$result = array(  );


$dbConn = mysql_connect ("localhost", DB_USER, DB_PASS) or die ('MySQL connect failed.');
mysql_select_db( DB_BASE ) or die('Cannot select database.');
mysql_query("SET NAMES utf8");



$isExistsBase = file_exists(FPATH_BASE);
$isExistsDelBase = file_exists(FPATH_TODELETE);
$isUpdateState = ( $isExistsBase || $isExistsDelBase )?true:false;

if($isUpdateState){
	fxRunUpdate();
}else{
	if( fxUnpackIncoming() ){
		fxRunUpdate();
	}else{
		fxAddResult('error', 'Входящих .zip пакетов не обнаружено.');
	}
}


exit( json_encode($result) );


/***************************************************************************/
function removeDirRec($dir)
{
    if ($objs = glob($dir."/*")) {
        foreach($objs as $obj) {
            is_dir($obj) ? removeDirRec($obj) : unlink($obj);
        }
    }
    @rmdir($dir);
}

function chmodDirRec($dir){
    if ($objs = glob($dir."/*")) {
        foreach($objs as $obj) {
            is_dir($obj) ? chmodDirRec($obj) : chmod($obj,0755);
        }
    }
    chmod($dir,0755);
}

function fxTransliteration($str){
    $tr = array(
        "А"=>"a","Б"=>"b","В"=>"v","Г"=>"g",
        "Д"=>"d","Е"=>"e","Ж"=>"j","З"=>"z","И"=>"i",
        "Й"=>"y","К"=>"k","Л"=>"l","М"=>"m","Н"=>"n",
        "О"=>"o","П"=>"p","Р"=>"r","С"=>"s","Т"=>"t",
        "У"=>"u","Ф"=>"f","Х"=>"h","Ц"=>"ts","Ч"=>"ch",
        "Ш"=>"sh","Щ"=>"sch","Ъ"=>"","Ы"=>"yi","Ь"=>"",
        "Э"=>"e","Ю"=>"yu","Я"=>"ya","а"=>"a","б"=>"b",
        "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
        "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
        "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
        "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
        "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
        "ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya", 
        " "=> "_", "."=> "_", "/"=> "_", "'"=>'_', '"'=>'_', ','=>'_',
		'@'=>'_', '*'=>'_', '+'=>'_', '?'=>'_','#'=>'_', '%'=>'_'
    );
    return strtr($str,$tr);    
}

function fxAddResult($key, $msg){
	global $result;
	if( !isset($result[$key]) ){
		$result[$key] = array();
	}
	$result[$key][] = $msg;
}


function fxRunUpdate(){
	$isDone = false;
    
	$isDelBase = file_exists(FPATH_TODELETE);
	if( $isDelBase ){
		fxAddResult('info', 'Обрабатываю пакет удаления');
		$cnt = fxTraverseDBA(FPATH_TODELETE, 'fxSqlDeleteProduct');
		fxAddResult('info', 'Обрабатано: '.$cnt['process'].' осталось: '.$cnt['remain']);
		if( $cnt['remain']==0){
			unlink(FPATH_TODELETE);
            $isDone = true;
		}		
	}

	$isBase = file_exists(FPATH_BASE);
	if( $isBase ){
		fxAddResult('info', 'Обрабатываю пакет добавления товаров');
		$cnt = fxTraverseDBA(FPATH_BASE, 'fxSqlUpdateProduct');
		fxAddResult('info', 'Обрабатано: '.$cnt['process'].' осталось: '.$cnt['remain']);
		if( $cnt['remain']==0){
			unlink(FPATH_BASE);
            $isDone &= true;
		}else{
			$isDone &= false;
		}
	}
    
    if($isDone){
        fxAddResult('done', '1');
        fxDB_RecalculateAllProductCount();
    }
}




function fxTraverseDBA( $file, $function){
	$hd = dbase_open($file, 2);
	
	$limit = DBA_READ_LIMIT;	
	$records = dbase_numrecords( $hd );
	$index = 1;

	if($records == 0){
		return array( 'remain'=>0, 'process'=>0 );
	}
	
	while ( $index<=$records && $limit>0 && (($record=dbase_get_record($hd, $index))!==false) ){
		$function( $record );
		dbase_delete_record($hd, $index);		
		$limit--;
		$index++;
	}
	dbase_pack($hd);
	dbase_close($hd);

	return array( 'remain'=> ($records-$index), 'process'=>$index );
}


function fxSqlUpdateProduct($data){
	foreach($data as &$vv){
		$vv = trim( mb_convert_encoding($vv, 'utf-8','cp866') );
	}
		
	if( count($data)!=9 ){
		fxAddResult('alert', 'Добавления продукта: ошибка формата'); 
		return false;
	}
	
	$entry = array( 'num'=>$data[0], 'name'=>$data[1], 'kod'=>$data[2], 'articul'=>$data[3], 'price'=>$data[4], 'upack'=>intval($data[5]), 'isenabed'=>$data[6], 'isnew'=>$data[7] );

	
	$catTree = explode('/', $entry['kod']);
	$catTreeCnt = count($catTree);
		
	//1. это категория?
	if( substr($entry['kod'],-1, 1)=='/' ){		
		$catId = intval($catTree[ ($catTreeCnt-2) ]);
		$parentId = 0;
		if( isset($catTree[ ($catTreeCnt-3) ]) ){
			$parentId = intval( $catTree[ ($catTreeCnt-3) ] );
		}
		
		$catExists = fxDB_is1cCategoryExists( $catId );
		if( $catExists ){
			fxDB_updateCategory($catId, $parentId, $entry);
		}else{
			fxDB_createCategory($catId, $parentId, $entry);
		}
		
	}else{ 
	//2. это товар
		$pId = intval($catTree[ ($catTreeCnt-1) ]);
		$parentId = 0;
		if( isset($catTree[ ($catTreeCnt-2) ]) ){
			$parentId = intval( $catTree[ ($catTreeCnt-2) ] );
		}

		$pExists = fxDB_is1cProductExists( $pId );
		if( $pExists ){
			fxDB_updateProduct($pId, $parentId, $entry);
		}else{
			fxDB_createProduct($pId, $parentId, $entry);
		}
        if( $fpic = fxGetProductImage( $pId ) ){
            fxDB_attachPictures($pId, $fpic);
        }
	}
	
}

function fxSqlDeleteProduct($rawdata){
    //$catTree = explode('/', trim($rawdata[2]) );
    //$catTreeCnt = count($catTree);
    $pId = intval($rawdata[ 0 ]);
	$sql = 'update '.DB_PREFIX.'_products set `enabled`=0 where id_1c='.$pId.' limit 1';
    fxDB_query($sql);
}

function fxDB_is1cCategoryExists($catid){
	$sql = 'select count(*) from '.DB_PREFIX.'_categories where id_1c='.$catid;
	list($result) = fxDB_fetchrow($sql);
	return ($result>0)?true: false;
}

function fxDB_is1cProductExists($pid){
    $sql = 'select count(*) from '.DB_PREFIX.'_products where id_1c='.$pid;
    list($result) = fxDB_fetchrow($sql);
    return ($result>0)?true: false;
}

function fxDB_RecalculateAllProductCount(){ //TODO!!!
    //$sq = 'select * from '.DB_PREFIX.'_categories ';
}

function fxDB_fetchParentCatBy1c($catid){
    $realParentId = 1;
    if( $catid!=0 ){
        list($realParentId) = fxDB_fetchrow('select categoryID from '.DB_PREFIX.'_categories where id_1c='.$catid);
    }
    if(empty($realParentId)){
        $realParentId=1;
    }
    return $realParentId;
}
function fxDB_fetchProductIdBy1c($id1c){
    list($realParentId) = fxDB_fetchrow('select productID from '.DB_PREFIX.'_products where id_1c='.$id1c.' limit 1');
    if(empty($realParentId)) return false;
    return $realParentId;
}

function fxDB_updateCategory ($catid, $parentid, $data){
	$catid = intval($catid);
	$parentid = intval($parentid);	
	
	$data['name']= mysql_real_escape_string( $data['name'] );
	
	$realParentId = fxDB_fetchParentCatBy1c($parentid);
	

	$sql = 'update '.DB_PREFIX.'_categories set `parent`='.$realParentId.', `products_count_admin`=0, `products_count`=0, `allow_products_comparison`=1, `allow_products_search`=1, `show_subcategories_products`=1, `name_ru`=\''.$data['name'].'\', `slug`=\''.fxTransliteration($data['name']).'\', `picture`=\'\', `name_en`=\'\', `description_en`=\'\', `meta_title_en`=\'\', `meta_description_en`=\'\',
     `meta_keywords_en`=\'\',   `meta_title_ru`=\'\', `meta_description_ru`=\'\', `meta_keywords_ru`=\'\'     
     where `id_1c`='.$catid.' limit 1';
	fxDB_query($sql);
}

function fxDB_createCategory ($catid, $parentid, $data){
	$catid = intval($catid);
	$parentid = intval($parentid);
		
	$data['name']= mysql_real_escape_string( $data['name'] );
	
	$realParentId = fxDB_fetchParentCatBy1c($parentid);

	$sql = 'insert into '.DB_PREFIX.'_categories (
    `parent`, `products_count_admin`, `products_count`,
    `picture`, `name_en`, `description_en`, `meta_title_en`, `meta_description_en`,
    `meta_keywords_en`,   `meta_title_ru`,     `meta_description_ru`,     `meta_keywords_ru`,
    `allow_products_comparison`, `allow_products_search`, `show_subcategories_products`, `name_ru`,
    `slug`, `id_1c` )
	values ('.$realParentId.', 0, 0,
     \'\',\'\',\'\',\'\',\'\',
     \'\',\'\',\'\', \'\',
     1, 1, 1, \''.$data['name'].'\',
      \''.fxTransliteration($data['name']).'\', '.$catid.' )';
    
	fxDB_query($sql);
}


function fxDB_updateProduct($pId, $parentId, $data){
	$pid = intval($pId);
	$parentid = intval($parentId);
		
	$data['name']= mysql_real_escape_string( $data['name'] );
	$data['price'] = (float) $data['price'];
	$data['articul'] = mysql_real_escape_string($data['articul']);
	$data['name'] = mysql_real_escape_string($data['name']);
    $data['isenabed'] = ($data['isenabled']>0)?1:0;
	
	$realParentId = fxDB_fetchParentCatBy1c($parentid);
	$pdescr = mysql_real_escape_string( fxGetProductDescr($data['kod']) );
    
    
	$sql = 'update '.DB_PREFIX.'_products set 
    `categoryID`='.$realParentId.' , 
     `Price`=\''.round($data['price'],3).'\' ,
     `enabled`='.$data['isenabed'].',
	 `ordering_available`=1,
     `product_code`=\''.$data['articul'].'\' ,
     `name_ru`=\''.$data['name'].'\' ,
     `description_ru`=\''.$pdescr.'\' 
     where `id_1c`= '.$pId.' limit 1';
	fxDB_query($sql);
    
    $id = fxDB_fetchProductIdBy1c($pId);
    if($id!==false)
        fxDB_insertProductOptionVal($id, 17, $data['upack']); //WARNING PLAIN ID
}

function fxDB_createProduct($pId, $parentId, $data){
	$pid = intval($pId);
	$parentid = intval($parentId);
		
	$data['name']= mysql_real_escape_string( $data['name'] );
	$data['price'] = (float) $data['price'];
	$data['articul'] = mysql_real_escape_string($data['articul']);
	$data['name'] = mysql_real_escape_string($data['name']);
    $data['isenabed'] = ($data['isenabled']>0)?1:0;
	
	$realParentId = fxDB_fetchParentCatBy1c($parentid);
    
	$pdescr = mysql_real_escape_string( fxGetProductDescr($data['kod']) );

	$sql = 'insert into '.DB_PREFIX.'_products ( `categoryID`, `Price`, `enabled`, `ordering_available`, `product_code`,  `name_ru`, `description_ru`,  `id_1c`, `in_stock` )
	values ('.$realParentId.', \''.round($data['price'],3).'\', '.$data['isenabed'].', 1, \''.$data['articul'].'\', \''.$data['name'].'\', \''.$pdescr.'\', '.$pid.', 100 )';
	fxDB_query($sql);
    
    $id = fxDB_lastid(DB_PREFIX.'_products');
    fxDB_insertProductOptionVal($id, 17, $data['upack']); //WARNING PLAIN ID
}

function fxDB_insertProductOptionVal($pid, $optid, $val ){
    $pid = (int)$pid;
    $optid = (int)$optid;
    $sql = 'select * from '.DB_PREFIX.'_product_options_values where productID='.$pid.' and optionID='.$optid.' limit 1';
    $qw = fxDB_query($sql);
    if( mysql_num_rows($qw)>0 ){
        $sql = 'update '.DB_PREFIX.'_product_options_values set option_value_ru=\''.mysql_real_escape_string($val).'\' where productID='.$pid.' and optionID='.$optid.' limit 1';
    }else{
        $sql = 'insert into '.DB_PREFIX.'_product_options_values  (`optionID`, `productID`, `option_type`,
          `option_show_times`, `option_value_ru`) values ( '.$optid.', '.$pid.', 0, 1, \''.mysql_real_escape_string($val).'\')';
    }
    fxDB_query($sql);
}

function fxDB_attachPictures($pId, $fname){
    $srcName = DIR_PROCESS.DS.FNAME_IMAGES.DS.$fname;
    $dstName = DIR_SITE_PICTURES.DS.$fname;
    copy( $srcName, $dstName );
    $sql = "INSERT '.DB_PREFIX.'_product_pictures (productID, filename ) VALUES( '$pId','". mysql_real_escape_string($fname) ."' ) ";
    fxDB_query($sql);
}

function fxDB_fethRealCategoryId($c1id){
	
}

function fxDB_query($sql){
	$qw=mysql_query($sql);
	if( mysql_errno()){
		fxAddResult('error-sql', 'sql ошибка: '.mysql_error().' sql:'.$sql);
	}
	return $qw;
}

function fxDB_fetchrow($sql){
	$qw=fxDB_query($sql);
	if( $qw){
		$row=mysql_fetch_row($qw);
		return $row;
	}
	return array();
}

function fxDB_fetchassoc($sql){
	$qw=fxDB_query($sql);
	if( $qw){
		$row=mysql_fetch_assoc($qw);
		return $row;
	}
	return array();
}

function fxDB_lastid($table){
	$qw=fxDB_query('select LAST_INSERT_ID() from `'.$table.'`');
	if( $qw){
		list($row) = mysql_fetch_row($qw);
		return $row;
	}
	return false;
}

function fxGetProductDescr($prodId){
    $fname = $prodId.'.html';
    if(empty($fname)) return '';
	$fname = DIR_PROCESS.DS.FNAME_DESCRIPTIONS.DS.$fname;
	if( !file_exists($fname) ){ return ''; }
	$content = file_get_contents($fname);
	return $content;
}

function fxGetProductImage($fname){
    if(empty($fname)) return false;
    $fname = DIR_PROCESS.DS.FNAME_IMAGES.DS.$fname;

    foreach( array('.jpg', '.png', '.bmp') as $ext ){
        if( file_exists($fname.$ext) ){ return $fname.$ext; }
    }

    return false;    
}


function fxUnpackIncoming(){
	$hdir = opendir( PATH.DS.DIR_INCOMING );

	if(!$hdir){
		fxAddResult('error', 'Не удалось открыть входящую директорию');
		return false;
	}
	
	$fname = '';
	while (($file = readdir($hdir)) !== false) {
		if( preg_match('/.*zip$/s', $file) ){
			$fname = $file;
			break;
		}
	}
	closedir($hdir);
	
	if(empty($fname)){
		fxAddResult('error','Zip пакетов не найдено.');
		fxAddResult('done',1);
		return false;
	}
	
	removeDirRec(PATH.DS.DIR_PROCESS);
	mkdir(PATH.DS.DIR_PROCESS, 0777);
	
	$zz = new PclZip( PATH.DS.DIR_INCOMING.DS.$fname);
	$result = $zz->extract(PCLZIP_OPT_PATH, PATH.DS.DIR_PROCESS );
	
	if ($result == 0) {
        fxAddResult('error','Ошибка при распаковке');
		return false;
    }
	
	chmodDirRec(PATH.DS.DIR_PROCESS);
	
	unlink(PATH.DS.DIR_INCOMING.DS.$fname);
	
	return true;
}
